# -*- encoding: utf-8 -*-
import os
import shutil
import markdown
import json
from mdx_math import MathExtension
from jinja2 import Environment, PackageLoader, select_autoescape

def read_posts(info, path):
    """
        read your all posts in path
        
        turn markdown to html
    """

    tags_archives = {}
    posts = []

    for post in info:
        #print(post)
        post_file = open(os.path.join(path, post["file"]), "r", encoding = "utf-8").read()
        md = markdown.Markdown(extensions=[MathExtension(enable_dollar_delimiter=True), 'fenced_code', 'footnotes', 'tables', 'toc'])
        
        temp = { "title":post["title"], "url" : post["url"] }

        for tag in post["tags"]:
            if tag in tags_archives.keys():
                tags_archives[tag].append(temp)
            else:
                tags_archives[tag]=[]
                tags_archives[tag].append(temp)
        
        temp = { "title":post["title"], "url": post["url"], "content": md.convert(post_file) }
        posts.append(temp)

    return tags_archives, posts

def make_link_html(links):
    """
        make links to html_list
    """
    s = ""

    for i in links:
        s += "<li class=\"list-group-item list-group-item-action\" >- <a href=\"{0}\">{1}</a></li>\n".format(i["url"], i["name"])
    
    s = "<ul class=\"list-group\">\n" + s + "</ul>"

    return s

def make_all_html(name, link_html, posts, tags_archives):
    """
        Rendering HTML to File
    """
    pwd=os.getcwd()
    __pwd=os.path.join(pwd,"html")
    postwd=os.path.join(__pwd,"post")
    if not os.path.exists(os.path.join(__pwd,"tags")):
        os.mkdir(os.path.join(__pwd, "tags"))
    if not os.path.exists(__pwd):
        os.mkdir(__pwd)
    if not os.path.exists(postwd):
        os.mkdir(postwd)
    if not os.path.exists(os.path.join(__pwd,"source")):
        shutil.copytree("source" , os.path.join(__pwd,"source"))
    else :
        shutil.rmtree(os.path.join(__pwd,"source"))
        shutil.copytree("source" , os.path.join(__pwd,"source"))

    env = Environment(
        loader=PackageLoader('oub', 'template'),
        autoescape=select_autoescape(['html'])
    )
    index_template = env.get_template("index.html")
    list_template = env.get_template("list.html")
    post_template = env.get_template("post.html")

    # Index
    html = index_template.render(title = name, link = link_html)
    f = open(os.path.join(__pwd,"index.html"), "w", encoding="utf-8")
    f.write(html)

    # Archives
    html = list_template.render(title="Archives", posts = posts, is_archives = 1, link=link_html)
    f = open(os.path.join(__pwd, "archives.html"), "w", encoding="utf-8")
    f.write(html)

    # Tags-Archives
    html = list_template.render(title="Tags", tags = tags_archives, is_archives = 2, link=link_html)
    f = open(os.path.join(__pwd, "tags.html"), "w", encoding="utf-8")
    f.write(html)

    # Each Tags
    for i in tags_archives:
        html = list_template.render(title=i, posts=tags_archives[i], is_archives=0, link = link_html)
        f = open(os.path.join(__pwd, "tags", i + ".html"), "w", encoding="utf-8")
        f.write(html)

    # Each posts
    for i in posts:
        html = post_template.render(title=i["title"], this_content=i["content"], link=link_html)
        this_post_wd = os.path.join(postwd,i['url']+".html")
        f = open(this_post_wd, 'w', encoding = "utf-8")
        f.write(html)


if __name__ == '__main__':
    print("start work\n")
    file_post = open(os.path.join(os.getcwd(),"post.json"),"r",encoding="utf-8").read()
    print("Open setting posts.json\n")

    setting = json.loads(file_post)
    name = setting["name"]
    links = setting["links"]
    posts_info = setting["posts"]
    posts_path = setting["path"]
    posts_info.sort(key= lambda k: k["date"])
    print("Finish Analysising of the json\n")

    tags_archives, posts = read_posts(posts_info, posts_path)
    print("Read OK\n")

    link_html = make_link_html(links)
    print("Making link to html\n")

    make_all_html(name, link_html, posts, tags_archives)
    print("Done")